<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/08/16
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\user;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use ImiApp\ApiServer\Api\Model\GoodsskuPrice;

use Imi\Cache\CacheManager as Cache;

/**
 * 拍卖成功👏
 * @Auth(name="token",nologin={"get_coupons_list","get_coupons_data","index4"})
 * @Controller("/user.auction_success/")
 */
class AuctionSuccess extends UserBean
{
    protected $noNeedLogin = ['no'];
    protected $noNeedRight = ['*'];


    /**
     * 获取拍中列表
     *
     * @param integer $page 页1
     * @param integer $limit 数量10
     * @param string $search 搜索
     * @param string $type_status 拍卖类型:1=贝壳竞拍,2=降价拍,3=升价拍,4=暗拍(降价拍),5=暗拍(升价拍)
     * @param string $status 状态:un=待操作,post=寄拍,buy=购买,timeout=超时
     * @return void
     * @Action
     */
    public function get_list(?int $page = 1, ?int $limit = 10,  $search = null,  $status = null, $type_status = null)
    {

        $page = $page ?: 1;
        $limit = $limit ?: 10;

        $where['user_id'] = $this->auth->user()->id;
        $orderRaw = 'end_time asc';

            // if ($goodscate_id) {
            //     if ($goodscate_id < 4) {
            //         switch ($goodscate_id) {
            //             case '1':
            //                 $orderRaw = 'end_time asc';
            //                 break;
            //             case '2':
            //                 $orderRaw = 'id asc';
            //                 break;
            //             case '2':
            //                 $orderRaw = 'end_time asc';
            //                 break;
            //             default:
            //                 $orderRaw = 'end_time asc';
            //                 break;
            //         }
            //     } else {
            //         $where['goodscate_id'] = $goodscate_id;
            //     }
            // }




        // if ($search)
        //     $where['title'] = ['like', '%' . $search . '%'];

        // $status = $status ?: '2';
        if($status)
            $where['status'] = $status;
        if ($type_status)
            $where['type_status'] = $type_status;

        $list = Db::name('auction_success')

            // ->whereEx($this->whereCom)

            ->whereEx($where)
            // ->whereIsNull('deletetime')
            ->orderRaw($orderRaw)
            ->page($page, $limit)
            ->select()
            ->getArray();
        if ($list) {
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldList($val);
            }
        }
        return $this->success('', $list);
    }


    //创建订单

    //去寄拍



    // /**
    //  * 获取拍卖带出价列表
    //  *
    //  * @param int $auction_id 拍卖id
    //  * @param integer $page 1
    //  * @param integer $limit 10
    //  * @Action
    //  * @return void
    //  */
    // public function get_auction_data2($auction_id, ?int $page, ?int $limit)
    // {
    //     $page = $page ?: 1;
    //     $limit = $limit ?: 10;
    //     $where['auction_id'] = $auction_id;

    //     $auction = $this->getAuctionData($auction_id);

    //     if (!$auction) {
    //         return $this->error('没有该活动', $id, CODE_拍卖活动不存在);
    //     }

    //     $first = Db::name('auction_offer')->whereEx($where)->orderRaw('id desc')->find();
    //     if ($first) {
    //         $first['user'] = $this->GetUserData1($first['user_id']);
    //         $first['date'] = date('m.d H:i:s', $first['time']);
    //     }

    //     $count = Db::name('auction_offer')->whereEx($where)->count();
    //     $list = Db::name('auction_offer')->whereEx($where)->orderRaw('id desc')->page($page, $limit)->select()->getArray();
    //     foreach ($list as $key => &$val) {
    //         $val['enroll'] = Db::name('auction_enroll')->where('auction_id','=',$auction_id)->where('user_id','=',$val['user_id'])->find();
    //         $val['user'] = $this->GetUserData1($val['user_id']);
    //         $val['date'] = date('m.d H:i:s', $val['time']);
    //     }

    //     return $this->success('出价列表', ['list' => $list, 'count' => $count ? $count : 0, 'first' => $first, 'auction' => $auction]);
    // }





    // /**
    //  * 详情页
    //  *
    //  * @param int $id 拍卖id
    //  * @return void
    //  * @Action
    //  */
    // public function get_auction_data($id)
    // {
    //     $auction = $this->getAuctionData($id);
    //     if (!$auction) {
    //         return $this->error('没有该活动', $id, CODE_拍卖活动不存在);
    //     }

    //     $this->AddViewlog(6, $id, $this->auth->user()->id);
    //     Db::name('auction')->where('id', '=', $id)->setFieldInc('views', 1)->update();

    //     switch ($auction['type_status']) {
    //         case '1':
    //             $拍卖类型 = '贝壳竞拍';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_贝壳竞拍)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         case '2':
    //             $拍卖类型 = '降价拍';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_降价拍)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         case '3':
    //             $拍卖类型 = '升价拍';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_升价拍)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         case '4':
    //             $拍卖类型 = '暗拍(降价拍)';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_暗拍_降)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         case '5':
    //             $拍卖类型 = '暗拍(升价拍)';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_暗拍_升)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         default:
    //             # code...
    //             break;
    //     }

    //     $auction = $this->ChangeFieldData($auction);
    //     return $this->success('ok', $auction);
    // }





    /**
     * 获取毫秒时间戳
     *
     * @return int
     */
    private function time()
    {
        return microtime(true) * 10000;
    }


    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function getAuctionData($id)
    {
        $auction = Db::name('auction')->where('id', '=', $id)->find();
        return $auction;
    }



    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldList(&$val)
    {
        $auction = $this->getAuctionData($val['auction_id']);
        $val['auction'] = $auction;
        return $val;
    }



    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeAuctionFieldList(&$val)
    {
       
        switch ($val['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';

          
                $_当前价格缓存_ = 'auction_price_' . (string)$val['id'];
                if (Cache::has('redis', $_当前价格缓存_)) {
                    $_当前价格_ = Cache::get('redis', $_当前价格缓存_);
                } else {
                    $_当前价格_ = (float)$val['start_price'];
                }
                $val['now_price'] = $_当前价格_;

                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }


        if ($val['status']==3 && $val['end_time'] > 0 && $val['end_time'] < time()) {
            if ($val['start_status'] == 'time') {
                //结束了
                $queue2 = \Imi\Queue\Facade\Queue::getQueue('auction');
                $message2 = new \Imi\Queue\Model\Message;
                //发布对列
                $message2->setMessage(json_encode(['type' => 'auction_finish' . $val['type_status'], 'auction' => $val], JSON_UNESCAPED_UNICODE));
                $queue2->push($message2);
            }
        }
    


        if ($val['start_status'] == 'number') {
            $number_num = Db::name('auction_enroll')->where('auction_id', '=', $val['id'])->count();
            $val['number_num'] = $number_num ?? 0;
        }


        $val['date_str'] = $this->TimeToStr($val['createtime']);
        if ($val['start_time'] > 0) {
            $val['start_date'] = date('Y-m-d H:i:s', $val['start_time']);

            if ($val['start_time'] > time())
                $val['have_start_s'] = $val['start_time'] - time();
        }

        if ($val['end_time'] > 0) {
            $val['end_date'] = date('Y-m-d H:i:s', $val['end_time']);

            if ($val['end_time'] > time())
                $val['have_end_s'] = $val['end_time'] - time();
        }



        $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        if ($val['store_id'] > 0)
            $val['store'] = $this->getStoreData2($val['store_id']);
        $val['goods'] = $this->GetGoodsShortDataById2($val['goods_id']);

        $val['goodssku_price_list'] = GoodsskuPrice::dbQuery()->whereIn('id', explode(',', $val['goods_sku_price_ids']))->fieldRaw('id,goods_sku_ids,image,price,goods_sku_text,stock')->select()->getArray();

        if ($val['minimum_price'] > 0) {
            $val['minimum_price'] = '有';
        } else {
            $val['minimum_price'] = '无';
        }
        // unset($val['minimum_price']); //卸载保留价
        return $val;
    }


    /**
     * 详情页改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldData($val)
    {

        switch ($val['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';

                if ($val['end_time'] < time()) {
                    if ($val['start_status'] == 'time') {
                        //结束了
                        $queue2 = \Imi\Queue\Facade\Queue::getQueue('auction');
                        $message2 = new \Imi\Queue\Model\Message;
                        //发布对列
                        $message2->setMessage(json_encode(['type' => 'auction_finish' . $val['type_status'], 'auction' => $val], JSON_UNESCAPED_UNICODE));
                        $queue2->push($message2);
                    }
                }
                $_当前价格缓存_ = 'auction_price_' . (string)$val['id'];
                if (Cache::has('redis', $_当前价格缓存_)) {
                    $_当前价格_ = Cache::get('redis', $_当前价格缓存_);
                } else {
                    $_当前价格_ = (float)$val['start_price'];
                }
                $val['now_price'] = $_当前价格_;
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }

        if ($val['start_status'] == 'number') {
            $number_num = Db::name('auction_enroll')->where('auction_id', '=', $val['id'])->count();
            $val['number_num'] = $number_num ?? 0;
        }


        $val['date_str'] = $this->TimeToStr($val['createtime']);
        if ($val['start_time'] > 0) {
            $val['start_date'] = date('Y-m-d H:i:s', $val['start_time']);

            if ($val['start_time'] > time())
                $val['have_start_s'] = $val['start_time'] - time();
        }

        if ($val['end_time'] > 0) {
            $val['end_date'] = date('Y-m-d H:i:s', $val['end_time']);

            if ($val['end_time'] > time())
                $val['have_end_s'] = $val['end_time'] - time();
        }


        $val['self_enroll'] = Db::name('auction_enroll')->where('auction_id', '=', $val['id'])->where('user_id', '=', $this->auth->user()->id)->count();
        $val['auction_offer'] = Db::name('auction_offer')->where('auction_id', '=', $val['id'])->where('user_id', '=', $this->auth->user()->id)->find();


        $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        if ($val['store_id'] > 0)
            $val['store'] = $this->getStoreData3($val['store_id']);
        $val['goods'] = $this->GetGoodsShortDataByIdAuction($val['goods_id']);

        $val['goodssku_price_list'] = GoodsskuPrice::dbQuery()->whereIn('id', explode(',', $val['goods_sku_price_ids']))->fieldRaw('id,goods_sku_ids,image,price,goods_sku_text,stock')->select()->getArray();

        // unset($val['minimum_price']); //卸载保留价
        if ($val['minimum_price'] > 0) {
            $val['minimum_price'] = '有';
        } else {
            $val['minimum_price'] = '无';
        }

        $val['rule_id'] = (int)$val['type_status'];
        // $val['after_sales_id'] = 8;
        $val['server_ensure_id'] = 100;
        $val['help_id'] = 99;

        return $val;
    }





    /**
     * 详情页改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldHistoryList($val)
    {

        switch ($val['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }
        unset($val['minimum_price']); //卸载保留价
        if ($val['user_id'] > 0)
            $val['user'] = $this->GetUserData1($val['user_id']);
        // if ($val['minimum_price'] > 0) {
        //     $val['minimum_price'] = '有';
        // } else {
        //     $val['minimum_price'] = '无';
        // }
        return $val;
    }






    /**
     * 获取用户信息头像昵称
     *
     * @param int $id 用户id
     * @return void
     */
    protected function GetUserData1($id)
    {
        return Db::name('user')->where('id', '=', $id)->fieldRaw('nickname,avatar')
            // ->cache($this->db_cache_set)
            ->find();
    }
}
